package cn.com.jenson.common;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * BasicBo <br>
 * 用于继承
 * <p>
 * 将Bo转换为Entity的方法类<br>
 * 及Bo公共方法类的集合
 * </p>
 *
 * @param <E> Entity
 * @param <B> Bo
 */
public abstract class BasicBo<E extends BasicEntity, B> {

    /**
     * 将 Bo 转换为 Entity
     *
     * @param b      Bo
     * @param eClass Entity的class
     * @return Entity
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public E toEntity(B b, Class<E> eClass) throws InstantiationException, IllegalAccessException {
        E e = eClass.newInstance();
        BeanUtils.copyProperties(b, e);
        return (E) e;
    }

    /**
     * 将 Bo集合 转换为 Entity集合
     *
     * @param bList  Bo集合
     * @param eClass Entity的class
     * @return Entity列表
     */
    public List<E> toEntities(List<B> bList, Class<E> eClass) {
        return bList.stream().map(item -> {
            try {
                return toEntity(item, eClass);
            } catch (InstantiationException |
                     IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

}
